package com.doge.calcalbum.business.sysalbum

import androidx.lifecycle.*

class SysAlbumViewModel(
    private val repository: SysAlbumRepository,
    private val albumId: Int,
    private val albumType: Int,
) : ViewModel() {
    val copyLoading = repository.copyLoading
    val initPictureLoading = repository.initPictureLoading
    val pictureList: LiveData<List<SysEntry>> =
        Transformations.switchMap(repository.sysPictureList) { transform(it) }

    val initVideoLoading = repository.initVideoLoading
    val videoList: LiveData<List<SysEntry>> =
        Transformations.switchMap(repository.sysVideoList) { transform(it) }

    fun copyToAlbum(data: List<SysEntry>, deleteOrigin: Boolean) {
        repository.copyToAlbum(data, albumId, albumType, deleteOrigin)
    }

    private fun transform(data: List<Pair<String, String>>?): LiveData<List<SysEntry>> {
        if (data.isNullOrEmpty()) return MutableLiveData()
        val transformed = data.map {
            SysEntry(filePath = it.second, false)
        }
        return MutableLiveData<List<SysEntry>>().also { it.value = transformed }
    }
}


class SysAlbumViewModelFactory(private val albumId: Int, private val albumType: Int) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        val repository = SysAlbumRepository.get()
        if (modelClass.isAssignableFrom(SysAlbumViewModel::class.java)) {
            return SysAlbumViewModel(repository, albumId, albumType) as T
        }
        //noinspection unchecked
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

